<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="roleDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 添加角色对话框区域 -->
      <el-dialog
        title="添加角色"
        :visible.sync="roleDialogVisible"
        width="50%"
        @close="resetRoleForm"
      >
        <el-form
          :model="addRolesList"
          :rules="addRoleRules"
          ref="addRoleRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesList.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="addRolesList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand" label="#">
          <!-- 权限视图区域 -->
          <template #default="scope">
            <el-row
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限渲染 -->
              <el-col :span="5">
                <el-tag
                  type="success"
                  closable
                  @close="removeRingts(scope.row, item1)"
                  >{{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="5">
                    <el-tag
                      type="danger"
                      closable
                      @close="removeRingts(scope.row, item2)"
                      >{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col
                    :span="4"
                    v-for="item3 in item2.children"
                    :key="item3.id"
                  >
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRingts(scope.row, item3)"
                      >{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editRole(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delet"
              @click="romoveRole(scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑角色对话框区域 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="resetRoleEdit"
    >
      <el-form
        :model="editRolesList"
        :rules="addRoleRules"
        ref="editRoleRef"
        label-width="100px"
      >
        <el-form-item label="角色ID">
          <el-input v-model="editRolesList.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
    
<script>
export default {
  data() {
    return {
      //角色列表 数据
      rolesList: [],
      //添加角色 数据
      addRolesList: {
        roleName: "",
        roleDesc: "",
      },
      //编辑角色 数据
      editRolesList: {},
      //添加角色对话框隐藏显示
      roleDialogVisible: false,
      //编辑角色对话框隐藏显示
      editDialogVisible: false,

      //分配权限对话框隐藏显示
      setRightsDialogVisible: false,
      //分配角色弹出对话框时，保存当前角色id
      currentRoleID: "",
      //权限列表数据
      rightsList: [],
      //添加角色表单验证规则
      addRoleRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      //树状权限列表展示属性
      treeProps: {
        children: "children",
        label: "authName",
      },
      //默认选中树状节点id值数组
      defKeys: [],
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("角色列表访问失败");
      }
      this.rolesList = res.data;
    },

    //对话框关闭重置表单并移除效验结果
    resetRoleForm() {
      this.$refs.addRoleRef.resetFields();
    },

    //添加角色事件
    async addRole() {
      //添加角色前进行表单预验证
      this.$refs.addRoleRef.validate(async (value) => {
        if (!value) {
          return this.$message.error("请核对信息");
        }
        const { data: res } = await this.$http.post("roles", this.addRolesList);
        if (res.meta.status !== 201) {
          return this.$message.error("添加角色失败");
        }
        this.$message.success("已添加新角色");
        this.roleDialogVisible = false;
        this.getRolesList();
      });
    },

    //编辑角色对话框
    async editRole(roleInfo) {
      const { data: res } = await this.$http.get("roles/" + roleInfo.id);
      if (res.meta.status !== 200) {
        return;
      }
      console.log(res.data.roleId);
      this.editRolesList = res.data;
      this.editDialogVisible = true;
    },
    //点击取消重置编辑角色表单
    resetRoleEdit() {
      this.$refs.editRoleRef.resetFields();
    },

    //发送编辑角色信息
    editRoleInfo() {
      //确认发送前进行表单预验证
      this.$refs.editRoleRef.validate(async (value) => {
        if (!value) {
          return this.$message.error("请核对信息");
        }

        const { data: res } = await this.$http.put(
          "roles/" + this.editRolesList.roleId,
          {
            roleName: this.editRolesList.roleName,
            roleDesc: this.editRolesList.roleDesc,
          }
        );
        if (res.meta.status !== 200) {
          console.log(res);
          return this.$message.error("编辑角色失败，请重试");
        }
        this.$message.success("编辑角色成功");
        this.editDialogVisible = false;
        this.getRolesList();
      });
    },

    //点击删除按钮移除角色
    async romoveRole(roleInfo) {
      //询问用户是否确认删除角色
      const confirmInfo = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(confirmInfo)
      if (confirmInfo !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        const { status: status } = await this.$http.delete(
          "roles/" + roleInfo.id
        );
        // console.log(res)
        if (status !== 200) {
          this.$message.error("删除失败");
        }
        // console.log(roleInfo)
        this.$message.success("删除成功");
        this.getRolesList();
      }
    },

    //点击权限标签删除对应权限
    async removeRingts(role, rights) {
      //询问用户是否确认删除权限
      const confirmInfo = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(confirmInfo)
      if (confirmInfo !== "confirm") {
        return this.$message.info("已取消删除");
      }

      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rights.id}`
      );
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error("删除权限失败");
      }
      this.$message.success("删除权限成功");
      role.children = res.data;
    },

    //展开分配权限对话框，获取数据
    async showRightsDialog(role) {
      //保存当前角色id，以便分配角色时使用
      this.currentRoleID = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取数据失败");
      }
      this.rightsList = res.data;
      //递归获取三级节点id
      this.getLeafKeys(role, this.defKeys);
      this.setRightsDialogVisible = true;

      console.log(this.rightsList);
    },
    //通过递归形式获取角色三级权限下id,并保存到defKeys中
    getLeafKeys(node, arr) {
      //如果当前节点不包含children属性则为三级权限
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    //监听分配权限对话框关闭事件，重置defKeys
    setRightDialogClosed() {
      this.defKeys = [];
    },

    //点击确定修改角色权限
    async setRoleRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const  res  = await this.$http.post(`roles/${this.currentRoleID}/rights` , {
        rids: idStr,
      });
      // console.log(keys);
      if (res.status !== 200) {
        return this.$message.error("修改角色权限失败");
      }
      this.$message.success("修改角色权限成功");
      this.setRightsDialogVisible = false;
      this.getRolesList();
    },
  },
};
</script>
    
<style lang='less' scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.el-row {
  display: flex;
  align-items: center;
}
</style>